package com.demo.Queue;

import org.junit.Test;

public class ThreadExecutor {
	/**
	 * 执行线程
	 */
	private Thread executeThread;
	/**
	 * 运行状态
	 */
	private volatile boolean isRunning = false;

	/**
	 * @param task 发生阻塞的线程任务
	 */
	public void execute(Runnable task) {
		executeThread = new Thread(() -> {

			// 子线程
			Thread childThread = new Thread(task);

			// 子线程设置为守护线程
			childThread.setDaemon(true);

			childThread.start();
			try {
				// 强行执行子线程，使其进入休眠状态（因为子线程执行的内容是 sleep 5s）
				childThread.join();
				isRunning = true;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
	}

	/**
	 * @param mills 强制结束任务的时长阈值
	 */
	public void shutdown(long mills) {
		long currentTime = System.currentTimeMillis();
		// 在子线程执行完前，isRunning 是 false，根据传入时间判断是否要中断
		while (!isRunning) {
			System.out.println(isRunning);
			if ((System.currentTimeMillis() - currentTime) >= mills) {
				System.out.println("任务超时，需要结束他!");
				// 前端线程中断后，子线程（守护线程）便中断了
				executeThread.interrupt();
				break;
			}
		}
		isRunning = false;
	}

	public static void main(String[] args) {

		ThreadExecutor executor = new ThreadExecutor();
		long start = System.currentTimeMillis();
		executor.execute(() -> {
			System.out.println("执行线程任务");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		executor.shutdown(2000);
		long end = System.currentTimeMillis();
		System.out.println(end - start);
	}

	/**
	 * 测试守护线程
	 */
	@Test
	public void testDaemon() {
		Thread daemonThread = new Thread(() -> {
			while (true) {
				try {
					System.out.println("i am alive");
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					System.out.println("finally block");
				}
			}
		});
		daemonThread.setDaemon(true);
		daemonThread.start();
		//确保 main 线程结束前能给 daemonThread 能够分到时间片
		try {
			Thread.sleep(800);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
